package broker

import (
	"gitee.com/tjccc/gomq/lib/logger"
	"sync"
)

type Topic struct {
	name         string
	commitIndexs map[int]int
	sendIndexs   map[int]int
	//Queue         *list.List
	elements [][]byte

	Subscriptions []*ConsumerGroup
	sync.RWMutex
	subMu sync.RWMutex
}

func NewTopic(topicName string) *Topic {
	return &Topic{
		name:          topicName,
		Subscriptions: make([]*ConsumerGroup, 0),
		//Queue:         list.New(),
		elements: make([][]byte, 0),
	}
}

func (t *Topic) PutMsg(data []byte) {
	t.Lock()
	defer t.Unlock()
	t.appendData(data)
	logger.Infof("topic[%s] get a message:%s", t.name, string(data))
	t.subMu.RLock()
	defer t.subMu.RUnlock()
	for _, cg := range t.Subscriptions {
		go func() {
			cg.NotifyMsg(t.name)
		}()
	}
}

func (t *Topic) AddSubscription(subscription *ConsumerGroup) {
	t.subMu.Lock()
	defer t.subMu.Unlock()
	t.Subscriptions = append(t.Subscriptions, subscription)
}

func (t *Topic) MessageSvc(req *GetMsgReq) (resp *GetMsgResp) {
	t.Lock()
	defer t.Unlock()

	return nil
}

func (t *Topic) appendData(data []byte) {
	t.elements = append(t.elements, data)
}
